// pages/ziyuandian/ziyuandian.js

import { setWatcher } from '../../utils/watch.js'
const util = require('../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    API_BASE_URL: util.API_BASE_URL,
    onec: true,
    tagIndex: 0,
    searchShow: false,
    searchVal: '',
    mySelectNum: 0, //我选择的数量
    leftBlockIndex: "",
    latitude: 25.075877,
    longitude: 117.017382,
    scale: 8,
    laftBlockList: [],
    pageShowStatus: 0,//0为都不显示，1显示点位详情，2显示推荐线路
    markers: [],
    marker: {},
    labelObj: {},//billid:label的对照，用于动态显示label
    calloutPositions: [],
    markerDetailShow: false,
    tjxlList: [],
    popupTripInfoShow: false,
    tjxlPk: '', // 推荐线路pk
    tjxlTitle: '', // 推荐线路标题
    tjxlShow: true,
    audioContext: null, //音频对象
    isPlaying: false,  // 新增播放状态标志
  },
  watch: {
    pageShowStatus(val) {
      this.data.audioContext.stop();
      this.setData({ isPlaying: false })
    }
  },
  //播放音频
  playVoice() {
    const { audioContext, isPlaying, API_BASE_URL } = this.data
    let voice_link = this.data.marker.voice_link;
    if (voice_link && voice_link.length > 0 && voice_link.startsWith('/')) {
      voice_link = voice_link.substring(1);
    }
    audioContext.src = API_BASE_URL + voice_link;
    console.log()
    if (!isPlaying && voice_link) {
      // 如果未播放，则开始播放
      audioContext.stop() // 先停止确保从头播放
      audioContext.play()
      this.setData({ isPlaying: true })
    } else {
      // 如果正在播放，则停止
      audioContext.stop()
      this.setData({ isPlaying: false })
    }
  },
  //推荐线路路线
  tjxlRoute(e) {
    const xttjxl_pk = e.currentTarget.dataset.item.billid;
    this.setData({
      leftBlockIndex: null
    })
    this.getMarkersList("", "", xttjxl_pk)
  },
  //前往AI选择
  goAiselect() {
    wx.navigateTo({
      url: '/pages/contactAI/contactAI',
    })
  },
  //我选择
  mySelect() {
    wx.navigateTo({
      url: '/pages/mySelect/mySelect',
    })
  },
  //关闭搜索框
  searchCancel() {
    this.setData({
      searchShow: false
    })
  },
  //展开搜索框
  searchOpen() {
    this.setData({
      searchShow: true
    })
  },
  //搜索
  onSearch() {
    if (this.data.searchVal == '') {
      this.setData({
        searchVal: '古田会议会址'
      })
    }
    this.setData({ leftBlockIndex: null });
    this.getMarkersList(this.data.searchVal);
  },
  //搜索框的完成事件
  onConfirm(e) {
    if (e.detail.value == '') {
      this.setData({
        searchVal: '古田会议会址'
      })
    }
    this.setData({ leftBlockIndex: null });
    this.getMarkersList(this.data.searchVal);
  },
  //关闭点位详情
  closeAddressDetails() {
    this.setData({
      pageShowStatus: 0
    })
  },
  //切换推荐路线详情展开or隐藏
  cutShowState(e) {
    this.setData({ tjxlShow: !this.data.tjxlShow })
  },
  //顶部标签切换
  tagControl(e) {
    const tagIndex = e.currentTarget.dataset.tagIndex;
    if (this.data.tagIndex != tagIndex) {
      this.setData({
        tagIndex
      })
      if (tagIndex == 1) {
        //切换到福建地图
        this.setData({
          'scale': 7,
        })
      } else {
        //切换到龙岩市地图
        this.setData({
          'scale': 8,
        })
      }
    }
  },
  //左侧选择
  leftBlockControl(e) {
    const leftBlockIndex = e.currentTarget.dataset.leftBlockIndex;
    if (this.data.leftBlockIndex != leftBlockIndex) {
      this.setData({
        searchShow: false,
        leftBlockIndex,
        pageShowStatus: 0,
        scale: 8
      })
      //根据资源分类查询资源点列表数据
      this.getMarkersList("", this.data.leftBlockIndex);
    }
  },
  //我选择and推荐线路
  xlToggle(e) {
    const index = e.currentTarget.dataset.index;
    if (this.data.pageShowStatus != index) {
      this.setData({
        pageShowStatus: index
      })
    } else {
      this.setData({
        pageShowStatus: 0
      })
    }
  },
  //生成行程单
  createTripBill(e) {
    const { tjxlPk, tjxlTitle } = e.currentTarget.dataset;
    this.setData({ popupTripInfoShow: true, tjxlPk, tjxlTitle })
    // 获取子组件实例
    const child = this.selectComponent('#popupTripinfo');
    // 调用子组件方法
    if (child) {
      child.init();
    }
  },
  //查看行程单详情
  lookTripBillDetail(e) {
    const billid = e.currentTarget.dataset.billid;
    wx.navigateTo({
      url: '/pagesTripbill/tripNominate/tripNominate?billid=' + billid,
    })
  },
  //获取已选择行程的数量
  getZydNumberForUser() {
    let _this = this;
    util.request('itf/common/hongpei/resource/getZydNumberForUser.json').then(res => {
      if (res.success) {
        _this.setData({
          mySelectNum: res.data
        })
      } else {
        util.showMsg({ msg: res.message || res.msg });
      }
    });
  },
  //获取推荐线路数据
  getTjxlData() {
    let _this = this;
    util.request('itf/common/hongpei/resource/queryRecommendRoute.json').then(res => {
      if (res.success) {
        let list = [];
        res.data.forEach((item, index) => {
          if (index == 0) {
            item.show = true;
          } else {
            item.show = false;
          }
          list.push(item);
        })
        _this.setData({
          tjxlList: list
        })
      } else {
        util.showMsg({ msg: res.message || res.msg });
      }
    });
  },
  //前往点位详情
  goPointDetails(e) {
    let billid = this.data.marker.billid;
    let is_collect = this.data.marker.is_collect;
    wx.navigateTo({
      url: '/pages/pointDetails/pointDetails?billid=' + billid + '&is_collect=' + is_collect,
    })
  },
  //查询左侧资源分类信息
  async getLaftBlockList() {
    let _this = this;
    await util.request('itf/common/hongpei/define/queryBillList.json', {
      billtype: 'zyfl',
      pageSize: '20',
      pageNo: "1"
    }).then(res => {
      if (res.success) {
        let laftBlockList = [{
          "id": "",
          "name": "全部"
        }];
        _this.setData({
          laftBlockList: []
        })
        let records = res.records;
        if (records) {
          for (let i = 0; i < records.length; i++) {
            let record = records[i];
            let item = {};
            item.id = record.billid;
            item.name = record.zyfl;
            laftBlockList.push(item);
            if (record.zyfl == '红色经典' && _this.data.onec) {
              _this.setData({
                leftBlockIndex: record.billid
              })
            }
          }
        }

        _this.setData({ laftBlockList })
      } else {
        util.showMsg({ msg: "获取资源分类失败！" });
      }
    });
  },
  //点击地图点位
  markertap(e) {
    const _this = this;
    const markerId = e.markerId;
    let billid = '';

    this.data.markers.forEach(item => {
      if (markerId == item.id) {
        billid = item.billid;
      }
    })
    wx.getLocation({
      type: 'wgs84', // 坐标类型：wgs84（国际标准）或 gcj02（国测局标准）
      success(res) {
        const latitude = res.latitude;  // 纬度
        const longitude = res.longitude; // 经度
        util.request('/itf/common/hongpei/resource/getResourceMsg.json', {
          billid,
          longitude,
          latitude
        }).then(res => {
          if (res.success) {
            _this.setData({
              pageShowStatus: 1,
              marker: res.data
            })
          } else {
            util.showMsg({ msg: res.message || res.msg })
          }
        });
      },
      fail(err) {
        console.error('获取位置失败：', err);
      }
    });
  },
  //根据资源分类查询资源点列表数据
  async getMarkersList(keyword = "", zyfl_pk = "", xttjxl_pk = "") {
    let _this = this;
    await util.request('itf/common/hongpei/resource/queryResourceList.json', {
      keyword: keyword,
      zyfl_pk: zyfl_pk,
      xttjxl_pk
    }).then(res => {
      if (res.success) {
        _this.setData({
          markers: []
        })
        let data = res.data;
        if (data) {
          data.forEach((item, index) => {
            item.id = index;
            item.width = 21;
            item.height = 25;
            if (item.slt) {
              item.iconPath = util.API_BASE_URL + "itf/common/att/download.do?attrId=" + item.slt;
            } else {
              item.iconPath = '/images/marker.png'
            }
            _this.data.labelObj[item.billid] = {
              content: item.zydmc, // 显示的名称
              color: '#ffffff', // 文字颜色
              fontSize: 12, // 文字大小
              borderRadius: 100, // 边框圆角
              bgColor: '#EA5555', // 背景颜色
              padding: 5, // 内边距
              display: 'ALWAYS', // 显示方式：ALWAYS 常显
              textAlign: 'center'  //文本对齐方式  left, right, center
            };
          })
        }
        _this.setData({ markers: data })
      } else {
        util.showMsg({ msg: "获取资源点失败！" });
      }
    });
  },

  //加入行程
  joinTravel(e) {
    wx.showLoading({
      title: '加入中...',
      mask: true
    })
    let joinIndex = "Y";
    let that = this;
    util.request('itf/common/hongpei/resource/addAndCancleTravel.json', {
      billid: that.data.marker.billid,
      operate_type: joinIndex
    }, "POST").then(res => {
      wx.hideLoading();
      if (res.success) {
        that.setData({
          'marker.is_join': joinIndex
        })
        that.setData({
          mySelectNum: res.data.zyd_number
        })
        util.showMsg({ msg: "已加入行程" });
      } else {
        util.showMsg({ msg: "加入行程失败！" });
      }
    });
  },
  //取消加入行程
  cancelJoinTravel(e) {
    wx.showLoading({
      title: '取消中...',
      mask: true
    })
    let that = this;
    let joinIndex = "N";
    util.request('itf/common/hongpei/resource/addAndCancleTravel.json', {
      billid: that.data.marker.billid,
      operate_type: joinIndex
    }, "POST").then(res => {
      wx.hideLoading();
      if (res.success) {
        this.setData({
          'marker.is_join': joinIndex
        })
        that.setData({
          mySelectNum: res.data.zyd_number
        })
        util.showMsg({ msg: "取消成功" });
      } else {
        util.showMsg({ msg: "取消失败！" });
      }
    });
  },
  //收藏
  collectTravel(e) {
    wx.showLoading({
      title: '收藏中...',
      mask: true
    })
    let that = this;
    let collectIndex = "Y";
    util.request('itf/common/hongpei/resource/addAndCancleZyd.json', {
      billid: that.data.marker.billid,
      operate_type: collectIndex
    }, "POST").then(res => {
      wx.hideLoading();
      if (res.success) {
        this.setData({
          'marker.is_collect': collectIndex
        })
        util.showMsg({ msg: "收藏成功" });
      } else {
        util.showMsg({ msg: "收藏失败！" });
      }
    });
  },
  //取消收藏
  cancelCollectTravel(e) {
    wx.showLoading({
      title: '取消收藏中...',
      mask: true
    })
    let that = this;
    let collectIndex = "N";
    util.request('itf/common/hongpei/resource/addAndCancleZyd.json', {
      billid: that.data.marker.billid,
      operate_type: collectIndex
    }, "POST").then(res => {
      wx.hideLoading();
      if (res.success) {
        this.setData({
          'marker.is_collect': collectIndex
        })
        util.showMsg({ msg: "取消收藏成功" });
      } else {
        util.showMsg({ msg: "取消收藏失败！" });
      }
    });
  },
  //去导航
  goNavigate(e) {
    const item = e.currentTarget.dataset.item;
    let xxdz = item.xxdz.split(",").join("");
    wx.openLocation({
      latitude: Number(item.latitude), // 目的地纬度
      longitude: Number(item.longitude), // 目的地经度
      name: item.name, // 目的地名称
      address: xxdz // 目的地地址
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    setWatcher(this)
    let audioContext = wx.createInnerAudioContext();
    audioContext.onError((err) => {
      console.error('音频播放错误:', err)
      this.setData({ isPlaying: false })
    })

    // 监听播放结束事件
    audioContext.onEnded(() => {
      this.setData({ isPlaying: false })
    })

    this.getTjxlData();
    this.setData({
      mapCtx: wx.createMapContext('map'),
      audioContext
    })
  },
  // 监听地图缩放变化
  onScaleChange(e) {
    const currentScale = e.detail.scale;
    if (currentScale) {
      this.updateLabelsVisibility(currentScale);
    }
  },

  // 更新标签可见性
  updateLabelsVisibility(scale) {
    var _this = this;
    const threshold = 9; // 缩放阈值，需根据实际情况调整
    var markers = _this.data.markers;
    for (var i = 0; i < markers.length; i++) {
      var marker = markers[i];
      var billid = marker.billid;
      if (scale >= threshold) {
        marker.label = _this.data.labelObj[billid];
      } else {
        delete marker.label;
        //marker.label = {};
      }
    }
    _this.setData({ markers })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  async onShow() {
    const token = wx.getStorageSync('token');
    const mapSort = wx.getStorageSync('mapSort');
    if (token) {
      this.getZydNumberForUser();
    }
    if (mapSort == '红色经典') {
      this.data.laftBlockList.forEach(item => {
        if (item.name == mapSort) {
          this.setData({
            leftBlockIndex: item.id
          })
          //根据资源分类查询资源点列表数据
          this.getMarkersList("", this.data.leftBlockIndex);
        }
      })
    }
    if (this.data.onec) {
      //查询左侧资源分类信息
      await this.getLaftBlockList();
      //根据资源分类查询资源点列表数据
      await this.getMarkersList("", this.data.leftBlockIndex);
      this.setData({ onec: false })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    this.setData({
      pageShowStatus: 0,
    })
    wx.removeStorageSync('mapSort')
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})